<?php
namespace
{
    //Register language helper function
    if (!function_exists('lang'))
    {
        function lang($text, $locale = null)
        {
            $lang = $locale == null ? \Library\Locale\Language::getDefault() : \Library\Locale\Language::getLanguage($locale);

            return $lang->translate($text);
        }
    }
}

namespace Library\Locale
{
    class Language
    {
        const JSON = 'json';
        const XML = 'xml';
        const INI = 'ini';

        private $_language = array();

        private static $_defaultLanguage;
        private static $_languages = array();

        public function __construct($file, $type = 'ini')
        {
            $this->_loadFile($file, $type);
        }

        public function translate($text)
        {
            $language = $this->_language;
            
            if (strpos($text, '.'))
            {
                $parts = explode('.', $text);
                
                $language = $language[$parts['0']];
                $text = $parts['1'];
            }
            
            if (isset($language[$text]))
            {
                return $language[$text];
            }

            if (isset($language[strtolower($text)]))
            {
                return $language[strtolower($text)];
            }
        }

        public static function registerLanguage($name)
        {
            self::$_languages[$name] = $this;
        }

        public static function getLanguage($name)
        {
            if (!isset(self::$_languages[$name]))
            {
                throw new \Exception('Language ' . $name . ' is not available.');
            }

            return self::$_languages[$name];
        }

        public static function getDefault()
        {
            if (self::$_defaultLanguage == null)
            {
                throw new \Exception('There is no default language adapter.');
            }

            return self::$_defaultLanguage;
        }

        public function setDefault()
        {
            self::$_defaultLanguage = $this;
        }

        private function _loadFile($filename, $type)
        {
            if (!file_exists($filename))
            {
                throw new \Exception('File ' . $filename . ' does not exist ');
            }

            switch($type)
            {
                case self::INI:
                    $this->_language = parse_ini_file($filename, true);
                    break;
                case self::XML:
                    throw new \Exception('Not implemented.');
                    break;
                case self::JSON:
                    throw new \Exception('Not implemented.');
                    break;
            }
        }
    }
}